﻿using Microsoft.AspNetCore.Mvc;
using Urs.Admin.Models.ExternalAuthentication;
using Urs.Core.Plugins;
using Urs.Data.Domain.Configuration;
using Urs.Services.Authentication.External;
using Urs.Services.Configuration;
using Urs.Services.Plugins;
using Urs.Services.Security;
using Urs.Framework.Controllers;
using Urs.Framework.Mvc;

namespace Urs.Admin.Controllers
{
    [AdminAuthorize]
    public partial class ExternalAuthController : BaseAdminController
	{
		#region Fields

        private readonly IOpenAuthenticationService _openAuthenticationService;
        private readonly ExternalAuthSettings _externalAuthenticationSettings;
        private readonly ISettingService _settingService;
        private readonly IPermissionService _permissionService;
        private readonly IPluginFinder _pluginFinder;

		#endregion

		#region Constructors

        public ExternalAuthController(IOpenAuthenticationService openAuthenticationService, 
            ExternalAuthSettings externalAuthenticationSettings,
            ISettingService settingService, IPermissionService permissionService,
            IPluginFinder pluginFinder)
		{
            this._openAuthenticationService = openAuthenticationService;
            this._externalAuthenticationSettings = externalAuthenticationSettings;
            this._settingService = settingService;
            this._permissionService = permissionService;
            this._pluginFinder = pluginFinder;
		}

		#endregion 

        #region Methods

        public IActionResult MethodUpdate(AuthenticationMethodModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageExternalAuthenticationMethods))
                return HttpUnauthorized();

            var eam = _openAuthenticationService.LoadExternalAuthenticationMethodBySystemName(model.SystemName);
            if (eam.IsMethodActive(_externalAuthenticationSettings))
            {
                if (!model.IsActive)
                {
                    //mark as disabled
                    _externalAuthenticationSettings.ActiveAuthenticationMethodSystemNames.Remove(eam.PluginDescriptor.SystemName);
                    _settingService.SaveSetting(_externalAuthenticationSettings);
                }
            }
            else
            {
                if (model.IsActive)
                {
                    //mark as active
                    _externalAuthenticationSettings.ActiveAuthenticationMethodSystemNames.Add(eam.PluginDescriptor.SystemName);
                    _settingService.SaveSetting(_externalAuthenticationSettings);
                }
            }
            var pluginDescriptor = eam.PluginDescriptor;
            pluginDescriptor.DisplayOrder = model.DisplayOrder;
            PluginManager.SavePluginDescriptor(pluginDescriptor);
            //reset plugin cache
            _pluginFinder.ReloadPlugins(pluginDescriptor);

            return new NullJsonResult();
        }

        #endregion
    }
}
